package com.lgx.common.web.listener;

import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.lgx.common.dao.ISystemConfigDao;
import com.lgx.common.entity.Dictionary;
import com.lgx.common.entity.SystemConfig;
import com.lgx.common.service.IDictionaryService;
import com.lgx.common.util.ImageConstants;
import com.lgx.common.web.Constants;
import com.lgx.common.web.util.DateUtils;
import com.lgx.common.web.util.DictUtils;
import com.lgx.right.entity.User;

/**
 * 统计在线用户数
 * 
 * @author acer
 *
 */
public class SessionListener implements HttpSessionListener,
		ServletContextListener, HttpSessionAttributeListener {

	protected Logger log = Logger.getLogger(this.getClass());
	
	//获取application对象
	ServletContext application = null ;
	
	//
	HttpSession  session  = null ;
	
	//存放在线用户数
	Set<User> onlineUsers = new HashSet<User>();

	@SuppressWarnings("unchecked")
	@Override
	public void attributeAdded(HttpSessionBindingEvent event) {
		this.session = event.getSession();
		//当session存在用户时,记录user
		if(this.session.getAttribute(Constants.LOGIN_USER) != null)
		{
			User user = (User) this.session.getAttribute(Constants.LOGIN_USER);
			boolean flag = true;
			onlineUsers = (HashSet<User>) this.application.getAttribute(Constants.ONLINE_USER);
			for(User u : onlineUsers)
			{
				if(user.getId() == u.getId())
				{
					flag = false;
					break;
				}
			}
			
			if(flag)
			{
				log.info("用户："+user.getUsername()+","+DateUtils.dateToChar(new Date(), DateUtils.DATE_FORMAT_ZH)+"登录.");
				onlineUsers.add(user);
				this.application.setAttribute(Constants.ONLINE_USER, onlineUsers);
			}
		}
	}

	@Override
	public void attributeRemoved(HttpSessionBindingEvent event) {

	}

	@Override
	public void attributeReplaced(HttpSessionBindingEvent event) {
		// TODO Auto-generated method stub

	}

	@Override
	public void contextDestroyed(ServletContextEvent event) {
		// TODO Auto-generated method stub

	}

	@SuppressWarnings("unchecked")
	@Override
	public void contextInitialized(ServletContextEvent event) {
		// tomcat启动时创建用于保存人数的application对象
		this.application = event.getServletContext() ;
		// 在线人数
		this.application.setAttribute(Constants.ONLINE_USER, this.onlineUsers);
		
    	ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(application);
    	
    	//数据字典
    	IDictionaryService dictionaryService = (IDictionaryService) ac.getBean("dictionaryService");
    	List<Object> objs = dictionaryService.initDictionary();
    	DictUtils.kinds = (List<Dictionary>) objs.get(0);
    	DictUtils.dicts = (List<List<Dictionary>>) objs.get(1);
    	

    	//图片库地址
    	ISystemConfigDao systemConfigDao = (ISystemConfigDao) ac.getBean("systemConfigDao");
    	SystemConfig config1 = systemConfigDao.findSystemConfigByCode(ImageConstants.IMG_SERVER_URL_SIGN);
    	ImageConstants.IMG_SERVER_URL = config1.getValue();
    	
    	this.application.setAttribute(ImageConstants.IMG_SERVER_URL_SIGN, ImageConstants.IMG_SERVER_URL);
    	
    	//商家外卡消费返利
    	Constants.MCREBATE_ORGOUTCARD_TYPE = Double.parseDouble(systemConfigDao.findSystemConfigByCode(Constants.MCREBATE_ORGOUTCARD_CODE).getValue());
    	this.application.setAttribute(Constants.MCREBATE_ORGOUTCARD_CODE,Constants.MCREBATE_ORGOUTCARD_TYPE);
    	
    	//推广站会员消费返利
    	Constants.MCREBATE_PROMOTIONSTATION_TYPE = Double.parseDouble(systemConfigDao.findSystemConfigByCode(Constants.MCREBATE_PROMOTIONSTATION_CODE).getValue());
    	this.application.setAttribute(Constants.MCREBATE_PROMOTIONSTATION_CODE,Constants.MCREBATE_PROMOTIONSTATION_TYPE);
    	
    	//推广中心充值返利
    	Constants.BRREBATE_PROMOTIONCENTER_TYPE = Double.parseDouble(systemConfigDao.findSystemConfigByCode(Constants.BRREBATE_PROMOTIONCENTER_CODE).getValue());
    	this.application.setAttribute(Constants.BRREBATE_PROMOTIONCENTER_CODE,Constants.BRREBATE_PROMOTIONCENTER_TYPE);
    	
    	//运营中心充值返利
    	Constants.BRREBATE_OPERATIONCENTER_TYPE = Double.parseDouble(systemConfigDao.findSystemConfigByCode(Constants.BRREBATE_OPERATIONCENTER_CODE).getValue());
    	this.application.setAttribute(Constants.BRREBATE_OPERATIONCENTER_CODE,Constants.BRREBATE_OPERATIONCENTER_TYPE);
	}

	@Override
	public void sessionCreated(HttpSessionEvent event) {
		this.session = event.getSession();
	}

	@SuppressWarnings("unchecked")
	@Override
	public void sessionDestroyed(HttpSessionEvent event) {
		this.session = event.getSession();
		//当session存在用户时,删除application中的user
		if(this.session.getAttribute(Constants.LOGIN_USER) != null)
		{
			User user = (User) this.session.getAttribute(Constants.LOGIN_USER);
			log.info("用户："+user.getUsername()+","+DateUtils.dateToChar(new Date(), DateUtils.DATE_FORMAT_ZH)+"登出.");
			onlineUsers = (HashSet<User>) this.application.getAttribute(Constants.ONLINE_USER);
			onlineUsers.remove(user);
			this.application.setAttribute(Constants.ONLINE_USER, onlineUsers);
			
			Constants.SESSION_TIMEOUT_FLAG = true;
		}
	}

}
